﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ComplexEventProcessing;
using Microsoft.ComplexEventProcessing.Adapters;
using WcfOutputAdapter.MeterEventServiceReference;
using System.Threading;

namespace WcfOutputAdapter
{
    internal sealed class WcfOutputPointAdapter : PointOutputAdapter 
    {
        private WcfOutputAdapterConfig config;
        private CepEventType eventType;
        private MeterEventServiceClient client = new MeterEventServiceClient();

        public WcfOutputPointAdapter(WcfOutputAdapterConfig config, CepEventType type)
        {
            this.config = config;
            this.eventType = type;
        }

        public override void Resume()
        {
            new Thread(this.ConsumeEvents).Start();
        }

        public override void Start()
        {
            new Thread(this.ConsumeEvents).Start();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.client.Close();
            }
            base.Dispose(disposing);
        }

        public void ConsumeEvents()
        {
            PointEvent currentEvent = default(PointEvent);

            while (true)
            {
                if (AdapterState.Stopping == AdapterState)
                {
                    Stopped();
                    return;
                }

                if (DequeueOperationResult.Empty == Dequeue(out currentEvent))
                {
                    Ready();
                    return;
                }


                if (currentEvent.EventKind == EventKind.Insert)
                {
                    //QUESTION: So how do I tell what the fields are at design time so I map them 
                    //correctly?
                    string MeterId = currentEvent.GetField<string>(0);
                    double Value = currentEvent.GetField<double>(2);
                    DateTime Timestamp = currentEvent.GetField<DateTime>(1);

                    //this is the event we are interested in, pass it along
                    client.SubmitMeterEvent(MeterId, Value, Timestamp);
                }

                ReleaseEvent(ref currentEvent);
            }

        }
    }
}
